package com.party.admin.web.controller.system;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.biz.system.MemberGroupBizService;
import com.party.admin.biz.system.MemberMerchantBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.input.system.BindMerchantInput;
import com.party.admin.web.dto.input.user.UpdateRefundPwdInput;
import com.party.admin.web.dto.output.system.MemberGroupListOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.city.Area;
import com.party.core.model.member.*;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.member.*;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.sign.IMemberSignService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysRoleService;
import com.party.core.service.wechat.IWechatDefaultTemplateService;
import com.party.core.service.wechat.IWechatMerchantsService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Nullable;
import java.text.ParseException;
import java.util.*;

/**
 * @ClassName MemberGroupController
 * @Description 机构用户
 * @Author yifeng
 * @Date 2019/9/11 9:28
 **/
@Controller
@RequestMapping(value = "")
public class MemberGroupController {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IMemberSignService memberSignService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private IMemberExternalAppService memberExternalAppService;
    @Autowired
    private IMemberPartnerService memberPartnerService;
    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;
    @Autowired
    private IMemberBankService memberBankService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private MemberMerchantBizService memberMerchantBizService;
    @Autowired
    private IWechatMerchantsService wechatMerchantsService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private IWechatDefaultTemplateService wechatDefaultTemplateService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private MemberBizService memberBizService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final Integer ONE_LEVEL_CHILD = 1;

    @Value("#{party['mic.url']}")
    private String micUrl;

    /**
     * 子账号列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @param sysRoleId   角色id
     * @return
     * @author yifeng
     * @date 10:05 2019/9/11
     **/
    @RequestMapping(value = "member/group/childList")
    public ModelAndView childList(MemberGroup member, Page page, CommonInput commonInput,
                                  String sysRoleId, String partnerId, Integer type) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childList");
        try {
            page.setLimit(20);
            member.setIsPartner(1);
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            if (StringUtils.isNotEmpty(partnerId)) {
                params.put("partnerId", partnerId);

                MemberGroup memberGroup = memberGroupService.get(partnerId);
                if (StringUtils.isEmpty(memberGroup.getPartnerId())) {
                    mv.addObject("isOneLevelChild",ONE_LEVEL_CHILD);
                    params.put("sysRoleId", sysRoleId);

                    SysRole sysRole = new SysRole();
                    sysRole.setType(RoleType.PARTNER_ROLE.getCode());
                    List<SysRole> sysRoles = sysRoleService.list(sysRole);
                    mv.addObject("sysRoles", sysRoles);

                    //判断一级子账号是不是行知公社
                    boolean isXZGS = sysRoleService.hasRole(partnerId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
                    mv.addObject("isXZGS",isXZGS);

                }

                List<MemberGroupOutput> members = memberGroupService.childListPage(member, params, page);
                mv.addObject("members", members);

                MemberGroup partner = memberGroupService.get(partnerId);
                mv.addObject("partnerName", partner.getRealname());
                mv.addObject("partnerId", partnerId);
                mv.addObject("pPartnerId", partner.getPartnerId());
            } else {
                mv.addObject("members", new ArrayList<Member>());
            }
            mv.addObject("member", member);
            mv.addObject("page", page);
            mv.addObject("input", commonInput);
            mv.addObject("sysRoleId", sysRoleId);
            mv.addObject("type",type);
        } catch (Exception e) {
            logger.error("合作商列表异常", e);
        }
        return mv;

    }

    /**
     * 去 增加/编辑子账号
     *
     * @param id        用户id
     * @param partnerId 上级id
     * @return
     * @author yifeng
     * @date 11:02 2019/9/11
     **/
    @RequestMapping(value = "member/group/childForm")
    public ModelAndView childForm(String id, String partnerId, Integer type) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childForm");
        if (StringUtils.isNotEmpty(id)) {
            MemberGroup member = memberGroupService.get(id);
            mv.addObject("member", member);
        }
        MemberGroup partner = memberGroupService.get(partnerId);
        mv.addObject("partnerId", partnerId);
        mv.addObject("partnerName", partner.getRealname());
        mv.addObject("type",type);
        return mv;
    }

    /**
     * 保存子账号
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/saveChild")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveChild(MemberGroup member, String partnerId, Integer type) {
        if (StringUtils.isEmpty(partnerId)) {
            return AjaxResult.error("上级id不能为空");
        }
        try {
            memberGroupBizService.checkAccountInfo(member);
            member.setPartnerId(partnerId);
            member.setPartnerIds(partnerId);
            memberGroupBizService.savePartnerBiz(member,type);

            memberSetService.initMemberSet(member.getId());
            // 保存合作商附属表  机构app签到
            memberSignService.getSet(member.getId());

            MemberPartner memberPartner = memberPartnerService.findByMemberId(member.getId());
            if (null == memberPartner) {
                MemberPartner partner = memberPartnerService.findByMemberId(partnerId);
                memberPartner = new MemberPartner();
                memberPartner.setMemberId(member.getId());
                memberPartner.setCreateBy(member.getId());
                memberPartner.setUpdateBy(member.getId());
                memberPartner.setPartnerRemark(partner.getPartnerRemark());
                memberPartner.setPartnerType(partner.getPartnerType());
                memberPartner.setSystemType(partner.getSystemType());
                memberPartnerService.insert(memberPartner);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("合作商保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("用户保存异常");
        }
    }

    /**
     * 保存合作商
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/savePartner")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult savePartner(@ModelAttribute("member") MemberGroup member, MemberPartner memberPartner,
                                  @ModelAttribute("memberGroupInfo") MemberGroupInfo memberGroupInfo) {
        try {
            memberGroupBizService.checkAccountInfo(member);
            if (StringUtils.isEmpty(member.getCopyrightName())) {
                member.setCopyrightName(member.getRealname());
            }
            memberGroupBizService.savePartnerBiz(member,null);
            memberGroupBizService.savePartnerOtherBiz(memberPartner, memberGroupInfo, member);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("合作商保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("用户保存异常");
        }
    }

    /***
     * jsp 传参映射    作用于这个方法  savePartner
     * @param webDataBinder
     */
    @InitBinder("member")
    public void userBinder(WebDataBinder webDataBinder) {
        webDataBinder.setFieldDefaultPrefix("member.");
    }

    /***
     * jsp 传参映射    作用于这个方法  savePartner
     * @param webDataBinder
     */
    @InitBinder("memberGroupInfo")
    public void userDetailBinder(WebDataBinder webDataBinder) {
        webDataBinder.setFieldDefaultPrefix("memberGroupInfo.");
    }

    /**
     * 验证用户名或者手机号
     *
     * @param key
     * @param value
     * @param userId
     * @param type
     * @param roleName
     * @return
     * @author yifeng
     * @date 11:40 2019/9/26
     **/
    @ResponseBody
    @RequestMapping("member/group/checkUniqueProperty")
    public AjaxResult checkUniqueProperty(String key, String value, String userId, Integer type, String roleName) {
        if (StringUtils.isEmpty(key)) {
            return AjaxResult.error("请选择验证用户名或是手机号");
        }
        if (StringUtils.isEmpty(value)) {
            return AjaxResult.error("请输入需要验证的值");
        }
        if ("mobile".equals(key) && null == type) {
            return AjaxResult.error("用户类型不能为空");
        }
        try {
            List<MemberGroup> members = memberGroupService.checkUserName(key, value, userId, type);
            if (members.size() > 0) {
                if (members.size() == 1) {
                    if (StringUtils.isNotEmpty(userId) && !userId.equals(members.get(0).getId())) {
                        return AjaxResult.success(false);
                    }
                    if (StringUtils.isNotEmpty(roleName)) {
                        boolean hasPartner = sysRoleService.hasRole(members.get(0).getId(), roleName);
                        if (hasPartner) {
                            return AjaxResult.success(false);
                        } else {
                            return AjaxResult.success(true);
                        }
                    }
                }
                return AjaxResult.success(false);
            }
            return AjaxResult.success(true);
        } catch (Exception e) {
            logger.error("验证用户名或手机号异常", e);
            return AjaxResult.error("验证用户名或手机号异常");
        }
    }

    /**
     * 合作商列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @param memberType
     * @param newStatus
     * @return
     */
    @RequestMapping(value = "system/member/partnerList")
    public ModelAndView partnerList(PartnerInfoDetails member, Page page, CommonInput commonInput, String memberType,
                                    String newStatus, String sysRoleId, Integer maturityStatus) {
        ModelAndView mv = new ModelAndView("system/memberGroup/partnerList");
        try {
            page.setLimit(20);
            member.setIsPartner(1);
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            params.put("sysRoleId", sysRoleId);

            //使用中 1;
            //已过期 2;
            params.put("maturityStatus", maturityStatus);


            SysRole sysRole = new SysRole();
            sysRole.setType(RoleType.PARTNER_ROLE.getCode());
            List<SysRole> sysRoles = sysRoleService.list(sysRole);
            mv.addObject("sysRoles", sysRoles);

            List<PartnerInfoDetails> members = memberGroupService.partnerListPage(member, params, page);
            List<Integer> authorizations = Lists.newArrayList();
            members.forEach(m -> {
                MemberExternalApp temp = memberExternalAppService.findByMemberIdAndDeployType(m.getId(), 0);
                if (null == temp || StringUtils.isEmpty(temp.getExternalAccountId())) {
                    authorizations.add(0);
                } else {
                    authorizations.add(1);
                }
            });
            mv.addObject("partnerType", member.getPartnerType());
            mv.addObject("members", members);
            mv.addObject("page", page);
            mv.addObject("input", commonInput);
            mv.addObject("memberType", memberType);
            mv.addObject("status", newStatus);
            mv.addObject("sysRoleId", sysRoleId);
            mv.addObject("authorizations", authorizations);
            mv.addObject("member", member);
            mv.addObject("maturityStatus", maturityStatus);
            //一级子账号
            mv.addObject("type",ONE_LEVEL_CHILD);
        } catch (Exception e) {
            logger.error("合作商列表异常", e);
        }
        return mv;
    }

    /**
     * 合作商
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "system/member/partnerForm")
    public ModelAndView parnterForm(MemberGroup member) {
        ModelAndView mv = new ModelAndView("system/memberGroup/partnerForm");
        String memberId = member.getId();
        if (StringUtils.isNotEmpty(memberId)) {
            member = memberGroupService.get(memberId);
            if (StringUtils.isEmpty(member.getCopyrightName())) {
                member.setCopyrightName(member.getRealname());
            }
            mv.addObject("member", member);

            MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(memberId);
            if (null != memberGroupInfo) {
                Double wthdrawalCharge = memberGroupInfo.getWithdrawalCharge();
                if (null != wthdrawalCharge && 0 != wthdrawalCharge) {
                    wthdrawalCharge = BigDecimalUtils.mul(wthdrawalCharge, 100);
                    memberGroupInfo.setWithdrawalCharge(wthdrawalCharge);
                }
            }

            mv.addObject("memberGroupInfo", memberGroupInfo);

            MemberBank account = memberBankService.findByMemberId(memberId);//当前合作商的提现账号
            mv.addObject("account", account);

            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                mv.addObject("inParent", industry.getParentId());
            }

            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                mv.addObject("arParent", area.getParentId());
            }

            MemberPartner memberPartner = memberPartnerService.findByMemberId(memberId);
            mv.addObject("memberPartner", memberPartner);
        } else {
            MemberGroupInfo memberGroupInfo = new MemberGroupInfo();
            memberGroupInfo.setExpirationTime(DateUtils.addYear(new Date(), 1));
            mv.addObject("memberGroupInfo", memberGroupInfo);
            try {
                Date time = DateUtils.today();
                mv.addObject("signingTime", time);
                mv.addObject("contractStartTime", time);
                mv.addObject("contractEndTime", DateUtils.addYear(1, "yyyy-MM-dd"));

            } catch (Exception e) {

            }
        }
        return mv;
    }

    /**
     * 保存合作商提现账号
     *
     * @param bank
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/savePartnerAccount")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult savePartnerAccount(MemberBank bank) {
        try {
            if (bank.getMemberId().isEmpty()) {
                return AjaxResult.error("会员ID为空");
            }
            if (StringUtils.isEmpty(bank.getId())) {//新建合作商账号（用于提现）
                memberBankService.insert(bank);
            } else {//修改合作商提现账号
                memberBankService.update(bank);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("合作商提现账号保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("合作商提现账号保存异常");
        }
    }

    /**
     * 修改密码
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/updatePwd")
    public AjaxResult updatePwd(MemberGroup member) {
        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                MemberGroup t = memberGroupService.get(member.getId());

                if (StringUtils.isNotEmpty(member.getPassword())) {
                    String encryptPassword = PasswordUtils.encryptPassword(member.getPassword());
                    t.setPassword(encryptPassword);
                    memberGroupService.update(t);
                }
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 修改退款密码
     *
     * @param updateRefundPwdInput
     * @param result
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/updateRefundPwd")
    public AjaxResult updateRefundPwd(@Validated UpdateRefundPwdInput updateRefundPwdInput, BindingResult result, String id) {
        try {
            AjaxResult ajaxResult = new AjaxResult();
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            if (StringUtils.isNotEmpty(id)) {
                MemberGroup t = memberGroupService.get(id);
                String old = updateRefundPwdInput.getOldPassword();
                if (StringUtils.isNotEmpty(old)) {
                    if (StringUtils.isEmpty(t.getRefundPassword())) {
                        ajaxResult.setSuccess(false);
                        ajaxResult.setDescription("原密码错误!");
                        return ajaxResult;
                    }
                    boolean isEquals = PasswordUtils.validatePassword(old, t.getRefundPassword());
                    if (!isEquals) {
                        ajaxResult.setSuccess(false);
                        ajaxResult.setDescription("原密码错误!");
                        return ajaxResult;
                    }
                }
                // 两次密码是否一致
                if (!updateRefundPwdInput.getNewPassword().equals(updateRefundPwdInput.getConfirmPassword())) {
                    ajaxResult.setSuccess(false);
                    ajaxResult.setDescription("两次密码输入不一致");
                    return ajaxResult;
                }
                String encryptPassword = PasswordUtils.encryptPassword(updateRefundPwdInput.getConfirmPassword());
                t.setRefundPassword(encryptPassword);
                memberGroupService.update(t);

                ajaxResult.setSuccess(true);
                return ajaxResult;
            }
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("用户id为空");
            return ajaxResult;
        } catch (Exception e) {
            logger.error("修改退款密码异常", e);
            return new AjaxResult(false);
        }
    }

    /**
     * 验证用户密码
     *
     * @param password
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/checkPassword")
    public boolean checkPassword(String password, String userId) {
        MemberGroup member = memberGroupService.get(userId);
        return PasswordUtils.validatePassword(password, member.getPassword());
    }

    /**
     * 密码
     *
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/verifyRefundPwd")
    public AjaxResult verifyRefundPwd(String password, String activityId) {
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("参数不能为空");
        }
        Activity activity = activityService.get(activityId);
        MemberGroup m = memberGroupService.getPartner(activity.getMember());
        boolean result = PasswordUtils.validatePassword(password, m.getRefundPassword());
        return AjaxResult.success(result);
    }

    /**
     * 查询是否有退款密码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/haveRefundPassword")
    public AjaxResult haveRefundPassword(String activityId) {
        if (StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("参数不能为空");
        }
        AjaxResult r = new AjaxResult();
        Activity activity = activityService.get(activityId);
        MemberGroup m = memberGroupService.getPartner(activity.getMember());
        if (StringUtils.isEmpty(m.getRefundPassword())) {
            r.setSuccess(false);
        } else {
            r.setSuccess(true);
        }
        return r;
    }

    /**
     * 设置退款密码
     *
     * @param rfp
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/setRefundPassword")
    public AjaxResult setRefundPassword(String rfp, String activityId) {
        if (StringUtils.isEmpty(rfp) || StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("参数不能为空");
        }
        AjaxResult r = new AjaxResult();
        Activity activity = activityService.get(activityId);
        MemberGroup m = memberGroupService.getPartner(activity.getMember());
        if (StringUtils.isEmpty(m.getRefundPassword())) {
            r.setSuccess(true);
            m.setRefundPassword(PasswordUtils.encryptPassword(rfp));
            memberGroupService.update(m);
        } else {
            r.setSuccess(false);
            r.setDescription("退款密码已经存在");
        }
        return r;
    }

    /**
     * @param memberId
     * @return
     */
    @RequestMapping(value = "system/member/merchantForm")
    public ModelAndView merchantForm(String memberId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/merchantForm");
        MemberGroup member = memberGroupService.get(memberId);
        List<WechatMerchants> wechatMerchantsList = wechatMerchantsService.listNoRelation(member.getDeployType(), memberId);

        MemberExternalApp memberExternalApp
                = memberExternalAppService.findByMemberIdAndDeployType(memberId, member.getDeployType());
        if (null == memberExternalApp) {
            memberExternalApp = new MemberExternalApp();
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
            WechatMerchants wechatMerchants = wechatMerchantsService.getSystem();
            memberExternalApp.setExternalAccountId(wechatOpenMember.getId());
            memberExternalApp.setExternalMerchantId(wechatMerchants.getId());
        }
        WechatOpenMember wechatOpenMember = new WechatOpenMember();
        wechatOpenMember.setDeployType(member.getDeployType());
        List<WechatOpenMember> wechatOpenMemberList = wechatOpenMemberService.listNoRelation(member.getDeployType(), memberId);
        mv.addObject("member", member);
        mv.addObject("memberExternalApp", memberExternalApp);
        mv.addObject("wechatMerchantsList", wechatMerchantsList);
        mv.addObject("wechatOpenMemberList", wechatOpenMemberList);
        mv.addObject("testPayUrl", micUrl + "pay/test_pay.html");
        return mv;
    }

    /**
     * 绑定商户信息
     *
     * @param input 输入视图
     * @return 绑定商户
     */
    @ResponseBody
    @RequestMapping("system/member/bindMerchant")
    public AjaxResult bindMerchant(BindMerchantInput input) {
        try {
            // 直接设置启用, 页面上屏蔽掉选择
            input.setOpenStatus(1);
            memberMerchantBizService.bindMerchant(input);
            // 授权后, 设置默认的模板信息
            List<String> eventNames = Arrays.asList("众筹成功推送", "众筹支持消息推送", "收到众筹回复推送");
            String r = wechatDefaultTemplateService.defaultTemplateMessage(eventNames, input.getMemberId(), false);
            logger.info("绑定商户默认模板的信息: {}", r);
        } catch (BusinessException be) {
            return new AjaxResult(false, be.getMessage());
        } catch (Exception e) {
            logger.error("绑定商户异常", e);
            return AjaxResult.error(e.getMessage());
        }
        return new AjaxResult(true);
    }

    @ResponseBody
    @RequestMapping("system/member/expireCheck")
    public AjaxResult expireCheck(String memberId) {
        try {
            String key = "EXPIRE_DATE_" + memberId;
            String value = stringJedis.getValue(key);

            Date date = null;
            if (StringUtils.isNotEmpty(value)) {
                try {
                    date = DateUtils.parse(value, "yyyy-MM-dd HH:mm:ss");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (null == date) {
                date = MemberFormUtil.getExpirationTimeById(memberId);
                if (null == date) {
                    throw new Exception();
                }
                stringJedis.setValue(key, DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
            }
            return AjaxResult.success(MemberFormUtil.isExpire(memberId, date));
        } catch (Exception e) {
            logger.error("获取过期时间异常：memberId-{}", memberId);
            return AjaxResult.error("获取过期时间异常");
        }
    }

    /**
     * 合作商
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "system/member/adminForm")
    public ModelAndView adminForm(MemberGroup member) {
        ModelAndView mv = new ModelAndView("system/memberGroup/adminForm");
        mv.addObject("type", 5);
        String memberId = member.getId();
        if (StringUtils.isNotEmpty(memberId)) {
            member = memberGroupService.get(memberId);
            mv.addObject("member", member);

            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                mv.addObject("inParent", industry.getParentId());
            }

            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                mv.addObject("arParent", area.getParentId());
            }
        }

        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);

        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);
        return mv;
    }

    /**
     * 保存管理员
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/saveAdmin")
    public AjaxResult saveAdmin(MemberGroup member) {
        try {
            memberGroupBizService.saveAdminBiz(member);
        } catch (Exception e) {
            logger.error("管理员保存异常", e);
            return AjaxResult.error("用户保存异常");
        }
        return AjaxResult.success();
    }

    /**
     * 用户列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "system/member/adminList")
    public ModelAndView adminList(MemberGroup member, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("system/memberGroup/adminList");
        try {
            page.setLimit(50);
            member.setIsAdmin(YesNoStatus.YES.getCode());
            member.setDelFlag("0");
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            mv.addObject("input", commonInput);

            List<MemberGroup> members = memberGroupService.webListPage(member, params, page);
            mv.addObject("members", members);
            mv.addObject("page", page);
        } catch (Exception e) {
            logger.error("用户列表异常", e);
        }
        return mv;
    }

    /**
     * 设置或取消设置管理员
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "system/member/setAdmin")
    public AjaxResult setAdmin(String id, Integer isAdmin) {
        try {
            MemberGroup member = memberGroupService.get(id);
            if (isAdmin == 0) {
                member.setIsAdmin(0);
//                member.setType(Member.MEMBER_PERSONAL);
                memberGroupService.update(member);
                SysRole adminRole = sysRoleService.getRole(RoleEnum.ADMIN_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
                List<SysRole> sysRoles1 = roleService.findByMemberId(member.getId(), RoleType.PLATFORM_ROLE.getCode());
                List<SysRole> sysRoles = Lists.newArrayList();
                sysRoles.addAll(sysRoles1);
                sysRoles.add(adminRole);
                for (SysRole sysRole : sysRoles) {
                    memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), member.getId());
                }
            } else if (isAdmin == 1) {
                member.setIsAdmin(1);
                member.setType(Constant.MEMBER_PLATFORM);
                memberGroupService.update(member);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 获取供应商
     *
     * @param member
     * @param page
     * @return
     */
    @RequestMapping("system/member/selectPartner")
    public ModelAndView selectPartner(MemberGroup member, Page page, Integer multi) {
        ModelAndView mv = new ModelAndView("system/memberGroup/selectPartner2");
        member.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        member.setOpenStatus(1);
        member.setIsPartner(YesNoStatus.YES.getCode());
        List<PartnerInfoDetails> memberList = memberGroupService.getPartnerListData(member, page);
        mv.addObject("memberList", memberList);
        mv.addObject("page", page);
        mv.addObject("member", member);
        mv.addObject("multi", multi);
        return mv;
    }

    /**
     * @Description:获取合作商详细信息
     * @Param: [member]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019-02-26-0026
     */
    @RequestMapping(value = "system/member/getPartnerInfo")
    public ModelAndView getPartnerInfo(Member member) {
        ModelAndView mv = new ModelAndView("system/memberGroup/partnerInfo");
        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                PartnerInfoDetails partnerInfoDetails = memberGroupInfoService.getPartnerInfoByMemberId(member);
                mv.addObject("member", partnerInfoDetails);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "system/member/getExpirationDate")
    public AjaxResult getExpirationDate(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("用户id为空");
        }
        MemberGroupInfo groupInfo = memberGroupInfoService.findByMemberId(memberId);
        if (null != groupInfo && null != groupInfo.getExpirationTime()) {
            return AjaxResult.success((Object) DateUtils.formatDate(groupInfo.getExpirationTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return AjaxResult.success();
    }

    /**
     * @return
     * @Author yifeng
     * @Description 用户列表
     * @Date 11:19 2019/4/29
     **/
    @RequestMapping(value = "member/group/memberList")
    public ModelAndView memberList() {
        ModelAndView mv = new ModelAndView("system/memberGroup/memberList");
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "member/group/api/list")
    public Map<String, Object> memberListData(MemberGroup member, Page page, CommonInput commonInput, String memberType, String newStatus) {
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("data", Lists.newArrayList());
        ret.put("count", 0);
        ret.put("code", 0);
        try {
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            memberBizService.appendUserStatus(memberType, newStatus, params);

            Object isXzgs = params.get("isXzgs");
            if (null != isXzgs) {
                params.put("roleCode", RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
            }

            long start = System.currentTimeMillis();
            List<MemberGroup> members = memberGroupService.webListPage(member, params, page);
            List<MemberGroupListOutput> outputs = LangUtils.transform(members, new Function<MemberGroup, MemberGroupListOutput>() {
                @Nullable
                @Override
                public MemberGroupListOutput apply(@Nullable MemberGroup input) {
                    MemberGroupListOutput output = new MemberGroupListOutput();
                    try {
                        MyBeanUtils.copyBeanNotNull2Bean(input, output);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (null != isXzgs && isXzgs.equals("1")) {
                        output.setIsXzgs(1);
                    }
                    return output;
                }
            });
            long end = System.currentTimeMillis();
            logger.info("用户列表加载用时：{}(ms)", (end - start));

            ret.put("count", page.getTotalCount());
            ret.put("data", outputs);
        } catch (Exception e) {
            logger.error("用户列表数据异常", e);
        }
        return ret;
    }

    /**
     * 解绑手机
     *
     * @param memberId 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "member/group/unbindPhone", method = RequestMethod.POST)
    public AjaxResult unbindPhone(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("用户编号不能为空");
        }
        try {
            MemberGroup member = memberGroupService.get(memberId);
            member.setMobile("");
            memberGroupService.update(member);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解绑手机异常", e);
            return AjaxResult.error("解绑手机异常");
        }
    }

    /**
     * 取消设置合作商
     *
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping(value = "system/member/cancelPartner")
    public AjaxResult cancelPartner(String id) {
        try {
            memberGroupBizService.cancelPartner(id);

            List<String> childIds = memberGroupService.getChild(id);
            for (String childId : childIds) {
                List<String> childIds2 = memberGroupService.getChild(childId);
                for (String s : childIds2) {
                    memberGroupBizService.cancelPartner(s);
                }
                memberGroupBizService.cancelPartner(childId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("取消合作商异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("取消合作商异常");
        }
    }

    /**
     * 查看子账号信息
     *
     * @param memberId id
     * @return
     * @author yifeng
     * @date 9:34 2019/10/16
     **/
    @RequestMapping(value = "member/group/getChildInfo")
    public ModelAndView getPartnerInfo(String memberId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childInfo");
        mv.addObject("member", memberGroupService.get(memberId));
        return mv;
    }

    /**
     * 初始化行知公社的特殊账号
     *
     * @return 交互结果 true/false
     * @author yifeng
     * @date 9:56 2019/10/24
     **/
    @ResponseBody
    @RequestMapping(value = "member/group/initXzgsSpecialAccount")
    public AjaxResult initXzgsSpecialAccount() {
        try {
            String logo = "http://txzapp-10052192.image.myqcloud.com/85a800e9937e4e4d8150774e63d654d7/image/1571654763928.jpg";
            memberGroupBizService.saveXzgsSpecialAccount(logo, XzgsAccountEnum.XZGS_JX.getKey(), XzgsAccountEnum.XZGS_JX.getValue());
            memberGroupBizService.saveXzgsSpecialAccount(logo, XzgsAccountEnum.XZGS_YJ.getKey(), XzgsAccountEnum.XZGS_YJ.getValue());
            memberGroupBizService.saveXzgsSpecialAccount(logo, XzgsAccountEnum.XZGS_QL.getKey(), XzgsAccountEnum.XZGS_QL.getValue());
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成行知公社特殊账号异常", e);
            return AjaxResult.error("生成行知公社特殊账号异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "member/group/initOneLevelChildAccount")
    public AjaxResult initOneLevelChildAccount() {
        try {
            List<String> partnerIds = memberGroupService.getAllPartnerIds();
            SysRole sysRole = sysRoleService.getRole("oneLevelChild", RoleType.SYSTEM_ROLE.getCode());

            for (String partnerId : partnerIds) {

                List<String> childIds = memberGroupService.getChild(partnerId);
                for (String childId : childIds) {
                    MemberSysRole memberSysRole = memberSysRoleService.findByMemberAndRole(childId, sysRole.getId());
                    if (null == memberSysRole) {
                        memberSysRole = new MemberSysRole();
                        memberSysRole.setMemberId(childId);
                        memberSysRole.setRoleId(sysRole.getId());
                        memberSysRoleService.insert(memberSysRole);
                    }
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("初始化一级子账号异常",e);
            return AjaxResult.error("生成行知公社特殊账号异常");
        }
    }


}
